1391 lines
53 KiB
TypeScript
1391 lines
53 KiB
TypeScript
/**
|
||
* features/chat/composables/useChatShipping.ts
|
||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||
* 依赖:shipping.api(任务/客户等)、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件维护会话任务摘要 + ui_state 同步,
|
||
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点);
|
||
* co8:shipping_batches 工作台轮询已下线,进度改由 shipping-processing projection 承接;
|
||
* 保留 resolvedShippingBatchNo / shippingBatchSummary 等 ref 供调用方兼容,不再发起批次网络请求。
|
||
*/
|
||
|
||
import {
|
||
computed,
|
||
onBeforeUnmount,
|
||
ref,
|
||
watch,
|
||
type ComputedRef,
|
||
type Ref,
|
||
} from 'vue';
|
||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||
import { 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,
|
||
createShippingMenuHandlers,
|
||
createShippingParseReviewHandlers,
|
||
createShippingSendHandlers,
|
||
createShippingUploadHandlers,
|
||
useShippingOrderExtractionRuns,
|
||
onNoticeBatchConversationChanging,
|
||
findLatestShippingTaskId,
|
||
getShippingMatchResultPayload,
|
||
getShippingParseReviewPayload,
|
||
sanitizeShippingConversationText,
|
||
} from '../shipping';
|
||
import { isShippingSpreadsheetFile } from '../shipping/shippingUploadPrompt';
|
||
import { extractExt } from '../constants/shipping';
|
||
import {
|
||
getWorkspaceShippingTask,
|
||
listWorkspaceShippingCustomerOptions,
|
||
confirmWorkspaceShippingCustomer,
|
||
type ShippingConversationWorkspace,
|
||
type ShippingTaskDetail,
|
||
type ShippingTaskSummary,
|
||
} from '@/features/chat/api/shipping.api';
|
||
import type {
|
||
ShippingBatchSummary,
|
||
ShippingBatchUiState,
|
||
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 { ChatMessageSendResult } from '../types/chat-turn.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<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>;
|
||
attachments: Ref<PendingAttachment[]>;
|
||
selectedKb: Ref<string>;
|
||
isUploadingAttachments: Ref<boolean>;
|
||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||
presetQuestion: ComputedRef<string>;
|
||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<boolean>;
|
||
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_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||
hooks?: SendMessageLifecycleHooks,
|
||
) => Promise<ChatMessageSendResult>;
|
||
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,
|
||
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 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 shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
|
||
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
|
||
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
|
||
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||
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;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 同步批次摘要占位(co8 已下线批次详情 API)。
|
||
*
|
||
* 核心逻辑:batchNo 为空时清空摘要;否则仅回填本地 batch_no 与已有 task 焦点,不发起网络请求。
|
||
* @param batchNo - 目标批次号
|
||
*/
|
||
const syncShippingBatchSummary = async (batchNo: string) => {
|
||
const normalized = String(batchNo || '').trim();
|
||
if (!normalized) {
|
||
shippingBatchSummary.value = null;
|
||
shippingBatchTasks.value = [];
|
||
return;
|
||
}
|
||
resolvedShippingBatchNo.value = normalized;
|
||
if (!activeShippingBatchNo.value) {
|
||
activeShippingBatchNo.value = normalized;
|
||
}
|
||
shippingBatchSummary.value = {
|
||
id: 0,
|
||
batch_no: normalized,
|
||
conversation_id: conversationId.value,
|
||
current_focus_task_no: resolvedShippingTaskId.value || null,
|
||
process_summary: null,
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 同步会话批次工作台(co8 已下线 conversation batches API)。
|
||
*
|
||
* 核心逻辑:保留调用签名供抽取 Run / 终态刷新链路兼容;始终清空 workspace 并返回 false,不发起网络。
|
||
* @param _options - 历史参数,保留兼容
|
||
* @returns 恒为 false
|
||
*/
|
||
const syncShippingConversationWorkspace = async (
|
||
_options?: { preferLatest?: boolean },
|
||
): Promise<boolean> => {
|
||
void _options;
|
||
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;
|
||
}
|
||
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) {
|
||
await syncShippingBatchSummary(batchNo);
|
||
recovered = true;
|
||
}
|
||
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) {
|
||
await syncShippingBatchSummary(batchNo);
|
||
recovered = true;
|
||
}
|
||
recovered = recovered || Boolean(activeShippingTaskDetail.value);
|
||
}
|
||
return recovered || Boolean(batchNo);
|
||
};
|
||
|
||
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
|
||
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
|
||
);
|
||
|
||
/**
|
||
* 切换会话上传摘要中的活动批次(co8 已下线,保留签名兼容)。
|
||
*
|
||
* 核心逻辑:批次工作台 API 已移除,调用时仅提示用户改由右侧 processing 工作台操作。
|
||
* @param batchNo - 目标批次号
|
||
* @returns 恒为 false
|
||
*/
|
||
const switchShippingBatch = async (batchNo: string) => {
|
||
const normalizedBatchNo = String(batchNo || '').trim();
|
||
if (!normalizedBatchNo) return false;
|
||
msg.warning(t('chat.shippingNoticeUi.batchSwitchRemoved'));
|
||
return false;
|
||
};
|
||
|
||
/**
|
||
* 清空当前聊天页绑定的发货任务上下文。
|
||
*
|
||
* 核心逻辑:在新建对话、切换 Agent 或离开发货任务场景时,主动清掉批次/任务/上传缓存,
|
||
* 避免会话摘要和待上传库存文件残留到下一次新会话。
|
||
*/
|
||
const resetShippingConversationState = () => {
|
||
// 新对话不会触发 onConversationIdChanging;必须在此清掉旧 Run,
|
||
// 否则右侧面板仍会将其作为当前会话的展示条件。
|
||
shippingOrderExtractionRuns.clearActiveRun();
|
||
shippingAutoFlowRequested.value = false;
|
||
pendingShippingUploadTaskId.value = '';
|
||
pendingShippingNoticeTaskId.value = '';
|
||
pendingShippingInventoryFile.value = null;
|
||
shippingInventorySelectionActive.value = false;
|
||
shippingInventorySelectionTaskId.value = '';
|
||
resolvedShippingTaskId.value = '';
|
||
resolvedShippingBatchNo.value = '';
|
||
activeShippingBatchNo.value = '';
|
||
shippingConversationWorkspace.value = null;
|
||
shippingBatchSummary.value = null;
|
||
shippingBatchTasks.value = [];
|
||
activeShippingTaskDetail.value = null;
|
||
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
|
||
|| 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,
|
||
});
|
||
|
||
/**
|
||
* 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
|
||
|| 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,
|
||
getActiveShippingTaskId,
|
||
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
|
||
loadHistory,
|
||
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 workflowRefreshTrigger = ref(0);
|
||
const bumpWorkflowRefresh = () => {
|
||
workflowRefreshTrigger.value += 1;
|
||
};
|
||
/** 侧栏/提交共用的当前聚焦用户可见任务(OT-…)。 */
|
||
const focusedConversationTaskNo = ref<string | null>(null);
|
||
const showShippingProgressWorkspace = ref(false);
|
||
const clearShippingFocus = () => {
|
||
focusedConversationTaskNo.value = null;
|
||
void router.replace({ path: route.path, query: { ...route.query, focus_task_no: undefined, focus_notice: undefined } });
|
||
};
|
||
const setFocusedConversationTaskNo = (taskNo: string | null) => {
|
||
focusedConversationTaskNo.value = String(taskNo || '').trim() || null;
|
||
};
|
||
const shippingOrderExtractionRuns = useShippingOrderExtractionRuns({
|
||
messages,
|
||
conversationId,
|
||
currentAgentId,
|
||
newLocalMessageId,
|
||
saveLocalMessageToBackend,
|
||
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
|
||
getOrderExtractionReview: shippingIntakes.getOrderExtractionReview,
|
||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||
syncShippingConversationWorkspace,
|
||
refreshShippingActions,
|
||
loadHistory,
|
||
onConversationResolved: async (resolvedConversationId) => {
|
||
const currentRouteId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
|
||
if (currentRouteId === resolvedConversationId) return;
|
||
await router.replace({
|
||
path: route.path,
|
||
query: { ...route.query, conversation_id: resolvedConversationId },
|
||
});
|
||
},
|
||
onRetryError: (message) => msg.error(message),
|
||
onWorkflowRefresh: bumpWorkflowRefresh,
|
||
getFocusedUserTaskNo: () => focusedConversationTaskNo.value,
|
||
setFocusedUserTaskNo: setFocusedConversationTaskNo,
|
||
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);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
}
|
||
};
|
||
|
||
/** 保存 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);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
msg.success(t('chat.shippingNoticeDuplicateResolved'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingNoticeDuplicateResolveFailed'));
|
||
done?.(false);
|
||
}
|
||
};
|
||
|
||
/** 人工采纳 Dify 兜底 Candidate,并刷新当前 Run 的审核快照。 */
|
||
const promoteShippingCandidate = async (candidateNo: string, done?: (success: boolean) => void) => {
|
||
try {
|
||
await shippingIntakes.promoteCandidate(candidateNo);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
msg.success(t('chat.shippingCandidatePromoted'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
done?.(false);
|
||
}
|
||
};
|
||
|
||
/** 人工驳回 Dify 兜底 Candidate,并刷新当前 Run 的审核快照。 */
|
||
const rejectShippingCandidate = async (candidateNo: string, done?: (success: boolean) => void) => {
|
||
try {
|
||
await shippingIntakes.rejectCandidate(candidateNo);
|
||
const candidate = shippingIntakes.noticeAttachments.value.flatMap((item) => item.candidates || []).find((item) => item.candidateNo === candidateNo);
|
||
if (candidate) await shippingOrderExtractionRuns.updateCandidateReviewSnapshot(candidate);
|
||
msg.success(t('chat.shippingCandidateRejected'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
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,
|
||
getActiveShippingTaskId,
|
||
startChatTurn,
|
||
refreshShippingActions,
|
||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||
getSelectedCandidateNos: shippingIntakes.getSelectedCandidateNos,
|
||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||
enqueueNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||
startOrderExtractionRun: (...args) => shippingOrderExtractionRuns.startRun(...args),
|
||
sendTemporaryInventoryMessage: async (assetNo, fileName) => sendMessage(
|
||
`我已上传库存文件:${fileName},请先检查文件结构并说明下一步。`,
|
||
currentAgentId.value,
|
||
selectedKb.value,
|
||
[],
|
||
{
|
||
shipping_temporary_inventory_asset_no: assetNo,
|
||
display_query: `上传库存文件:${fileName}`,
|
||
},
|
||
),
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
// 快览完成后补充可见的用户请求;用户已输入备注时绝不覆盖。
|
||
watch([isShippingNoticeAgent, shippingIntakes.allParsedReady], ([isShippingAgent, allParsedReady]) => {
|
||
if (!isShippingAgent || !allParsedReady || input.value.trim()) return;
|
||
input.value = t('chat.shippingOrderExtractionDefaultUserMessage');
|
||
});
|
||
|
||
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
|
||
isThinking,
|
||
currentAgentId,
|
||
getActiveShippingTaskId,
|
||
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
|
||
messages,
|
||
sendShippingMenuMessage,
|
||
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,
|
||
startOrderExtractionRun: shippingOrderExtractionRuns.startRun,
|
||
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) {
|
||
focusedConversationTaskNo.value = null;
|
||
void shippingIntakes.restoreForConversation(nextId);
|
||
void shippingOrderExtractionRuns.restoreForConversation(nextId);
|
||
} else {
|
||
shippingOrderExtractionRuns.clearActiveRun();
|
||
}
|
||
if (prevId !== nextId) {
|
||
resolvedShippingTaskId.value = '';
|
||
if (!shippingBatchNoFromQuery.value) {
|
||
resolvedShippingBatchNo.value = '';
|
||
shippingBatchSummary.value = null;
|
||
shippingBatchTasks.value = [];
|
||
}
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 重试当前聚焦批次中可恢复的失败/排队任务(co8 已下线,保留签名兼容)。
|
||
*
|
||
* 核心逻辑:批次重试 API 已移除,调用时提示用户改由 processing 工作台或任务动作重试。
|
||
* @returns 恒为 null
|
||
*/
|
||
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
|
||
started: number;
|
||
skipped: number;
|
||
} | null> => {
|
||
msg.warning(t('chat.shippingNoticeUi.batchRetryRemoved'));
|
||
return null;
|
||
};
|
||
|
||
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) => !isShippingSpreadsheetFile(file, extractExt));
|
||
const spreadsheetFiles = files.filter((file) => isShippingSpreadsheetFile(file, extractExt));
|
||
if (noticeFiles.length) {
|
||
void shippingIntakes.enqueueNoticeFiles(noticeFiles);
|
||
}
|
||
// 表格附件先留在本地等待用户声明;不能因扩展名直接送订单或库存解析。
|
||
for (const file of spreadsheetFiles) {
|
||
attachments.value = [
|
||
...attachments.value,
|
||
{
|
||
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||
kind: 'local',
|
||
file,
|
||
type: '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();
|
||
};
|
||
|
||
/**
|
||
* 启停发货会话状态短轮询。
|
||
*
|
||
* 核心逻辑:co8 后不再轮询 shipping_batches;仅在存在任务上下文时每 3 秒补拉任务详情与动作按钮,
|
||
* 批次/处理进度改由 shipping-processing projection 承接。
|
||
*/
|
||
const restartShippingStatusPolling = () => {
|
||
if (shippingStatusPollTimer) {
|
||
clearInterval(shippingStatusPollTimer);
|
||
shippingStatusPollTimer = null;
|
||
}
|
||
if (!isShippingNoticeAgent.value) return;
|
||
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||
if (!taskId) return;
|
||
|
||
shippingStatusPollTimer = setInterval(() => {
|
||
if (!isShippingNoticeAgent.value) return;
|
||
const nextTaskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||
if (!nextTaskId) return;
|
||
void (async () => {
|
||
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,
|
||
prepareMarkdownDisplayText,
|
||
shippingAutoFlowRequested,
|
||
shippingInventoryPickerRef,
|
||
shippingNoticePickerRef,
|
||
pendingShippingUploadTaskId,
|
||
shippingInventorySelectionActive,
|
||
shippingInventorySelectionTaskId,
|
||
allowsSendWithAttachmentsOnly,
|
||
shippingTaskIdFromQuery,
|
||
shippingBatchNoFromQuery,
|
||
resolvedShippingBatchNo,
|
||
activeShippingBatchNo,
|
||
shippingConversationWorkspace,
|
||
shippingBatchSummary,
|
||
shippingBatchTasks,
|
||
isShippingActionBusy,
|
||
activeShippingTaskDetail,
|
||
getCurrentShippingChatContext,
|
||
getActiveShippingBatchNo,
|
||
switchShippingBatch,
|
||
retryCurrentShippingBatchPendingTasks,
|
||
queryShippingShortageDetails,
|
||
resetShippingConversationState,
|
||
resumeShippingTaskFromQuery,
|
||
getShippingMatchResultPayload,
|
||
getShippingParseReviewPayload,
|
||
updateShippingParseReviewHeader,
|
||
updateShippingParseReviewLine,
|
||
addShippingParseReviewLine,
|
||
removeShippingParseReviewLine,
|
||
handleShippingActionClick,
|
||
handleShippingInventorySelected,
|
||
finalizeShippingAssistantMessage,
|
||
selectShippingInventoryUploadTask,
|
||
cancelShippingInventoryTaskSelection,
|
||
shippingSuggestedPrompt,
|
||
useShippingSuggestedPrompt,
|
||
enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||
handleShippingLocalFilesSelected,
|
||
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
|
||
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
|
||
retryOrderExtractionRun: shippingOrderExtractionRuns.retryRun,
|
||
refreshOrderExtractionRun: shippingOrderExtractionRuns.refreshRun,
|
||
cancelOrderExtractionRun: shippingOrderExtractionRuns.cancelRun,
|
||
cancelOrderExtractionUnit: shippingOrderExtractionRuns.cancelUnit,
|
||
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
|
||
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
|
||
workflowRefreshTrigger,
|
||
bumpWorkflowRefresh,
|
||
focusedConversationTaskNo,
|
||
setFocusedConversationTaskNo,
|
||
clearShippingFocus,
|
||
showShippingProgressWorkspace,
|
||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||
setShippingCandidateSelected,
|
||
resolveShippingCandidateDuplicate,
|
||
promoteShippingCandidate,
|
||
rejectShippingCandidate,
|
||
showShippingDuplicateDialog,
|
||
showShippingCustomerDialog,
|
||
shippingCustomerOptions,
|
||
shippingCustomerLoading,
|
||
openShippingCustomerDialog,
|
||
searchShippingCustomers,
|
||
confirmShippingCustomer,
|
||
closeShippingCustomerDialog: () => {
|
||
showShippingCustomerDialog.value = false;
|
||
},
|
||
shippingDuplicateAttachment,
|
||
canForceCreateShippingDuplicate,
|
||
openShippingDuplicateDialog,
|
||
resolveShippingDuplicateDialog,
|
||
removeShippingDuplicateDialogAttachment,
|
||
closeShippingDuplicateDialog: () => {
|
||
showShippingDuplicateDialog.value = false;
|
||
},
|
||
tryHandleShippingAttachmentAutoFlow,
|
||
tryHandleShippingSend,
|
||
onConversationIdChanging,
|
||
onConversationLoadedEmpty,
|
||
onConversationLoadFailed,
|
||
};
|
||
}
|